package com.polaris.live.viewmodel.home

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.net.homeService
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.resp.go_resp.UserIdsBean
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * HomeRecommendViewModel
 *
 * @author Created by lucas on 2023/10/17 16:36
 * @since 1.0.0
 */
class HomeRecommendViewModel : BaseViewModel() {

    val listLiveData = MutableLiveData<ResultState<List<DisplayUserBean>>>()
    val refreshLiveData = MutableLiveData<ResultState<List<DisplayUserBean>>>()

    private var refreshRecommendListJob: Job? = null

    fun getRecommendList(currentUserId: Long? = null) {
        refreshRecommendListJob?.cancel()
        request({ homeService.getRecommendList(currentUserId) }, listLiveData)
    }

    fun refreshRecommendList(currentUserId: Long?) {
        refreshRecommendListJob = viewModelScope.launch {
            try {
                request({ homeService.getRecommendList(currentUserId) }, refreshLiveData)
            } finally {
                if (refreshRecommendListJob == coroutineContext[Job]) {
                    refreshRecommendListJob = null
                }
            }
        }
    }

    val itemLiveData = MutableLiveData<Pair<Int, DisplayUserBean>>()
    fun getDisplayUser(index: Int, userId: Long) {
        request({ homeService.getDisplayUsers(UserIdsBean(userId)) }, {
            if (it.isNotEmpty()) {
                itemLiveData.value = index to it.first()
            }
        })
    }
}